package utils


type RetryHandleFn func () (bool, error)

//返回的err不会影响是否停止retry
//isSuccess也会停止retry（是因为操作成功）
//目前主要用于乐观锁的重试
func RetryHandle(fn RetryHandleFn, maxtime... int) (error){
	var maxRetry = 6 //默认为retry 6次

	var err error
	var needRetry bool
	if len(maxtime) > 1 {
		panic("RetryHandle too many parameter")
	}

	if len(maxtime) == 1 {
         maxRetry = maxtime[0]
	}

	var retryTime = maxRetry
	for retryTime > 0 {
		retryTime -= 1
		needRetry, err = fn()
		/*if err != nil {
			return err
		}*/
		if !needRetry {
			return err
		} else {
			continue
		}
	}

	return err //errors.New("Retry exceece max times")
}

type RetryHandleForErrFn func () (error)
func RetryHandleForErr(fn RetryHandleForErrFn, retryErr error, maxtime... int) (error){
	var maxRetry = 6 //默认为retry 6次

	var err error
	//var needRetry bool
	if len(maxtime) > 1 {
		panic("RetryHandle too many parameter")
	}

	if len(maxtime) == 1 {
		maxRetry = maxtime[0]
	}

	var retryTime = maxRetry
	for retryTime > 0 {
		retryTime -= 1
		err = fn()
		/*if err != nil {
			return err
		}*/
		if err != retryErr {
			return err
		} else {
			continue
		}
	}

	return err //errors.New("Retry exceece max times")
}

type RetryFnForOptimisticLock func () (int64, error)
func RetryHandleForOptimisticLock(fn RetryFnForOptimisticLock, maxtime... int) (error){
	var maxRetry = 20 //默认为retry 20次

	var err error
	//var needRetry bool
	if len(maxtime) > 1 {
		panic("RetryHandle too many parameter")
	}

	if len(maxtime) == 1 {
		maxRetry = maxtime[0]
	}

	var retryTime = maxRetry
	for retryTime > 0 {
		retryTime -= 1
		affectedRows, err := fn()
		if err != nil {
			return err
		}

		if affectedRows != 0 {
			return err
		} else {
			continue
		}
	}

	return err //errors.New("Retry exceece max times")
}
